package com.kfm.controller;

import com.kfm.commons.AjaxResult;
import com.kfm.config.FileConfig;
import com.kfm.entity.Directory;
import com.kfm.entity.User;
import com.kfm.service.DirectoryService;
import com.kfm.service.FileService;
import com.kfm.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/file")
@CrossOrigin("*")
public class FileController {

    @Resource
    UserService userService;

    @Resource
    FileService fileService;

    @Resource
    DirectoryService directoryService;


    /**
     * 获取用户的所有目录
     * @param userId 用户id
     * @return AjaxResult（code 请求成功与否，请求结果信息，用户的目录信息/null)
     */
    @GetMapping("/getDir")
    public AjaxResult getDir( Integer userId) {
        User user = userService.selectByPrimaryKey(userId);
        // 通过文件表查询用户的所有目录
        List<com.kfm.entity.File> files = fileService.selectByUserId(userId);
        if (files.size() > 0) {
            return AjaxResult.success(files);
        } else {
            return AjaxResult.fail("查询失败");
        }
    }

    @RequestMapping("/getFiles")
    public AjaxResult getFiles(Integer id) {
        List<com.kfm.entity.File> files = fileService.selectByDirectoryId(id);
        return files.size() > 0 ? AjaxResult.success(files) : AjaxResult.fail("查询失败");
    }

    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file, Integer userId, Integer directoryId, String currentPath) throws IOException {
        // 上传操作 校验是否存在相同的文件
        if (file != null) {
            InputStream upload = file.getInputStream();
            String md5Hex = DigestUtils.md5Hex(upload);
            // 使用当前的MD5加密值及目录id查找是否存在相同的文件
            com.kfm.entity.File file2 = fileService.selectByMD5AndDirectoryId(md5Hex, directoryId);
            if (file2 == null) {
                User currentUser = userService.selectByPrimaryKey(userId);
                Directory directory = directoryService.selectByPrimaryKey(directoryId);
                // 如果选择了上传目录，那么就是 根目录 + 用户名 + 目录名，否则默认上传到 “我的资源”
                String path = FileConfig.getLocalPath() + File.separator + currentUser.getUsername() + File.separator
                        + (directory == null ? "我的资源" : directory.getDirectoryName());
                String target = path + File.separator + file.getOriginalFilename();
                file.transferTo(new File(target));
                com.kfm.entity.File file1 = new com.kfm.entity.File();
                file1.setUserId(userId);
                file1.setFileName(file.getOriginalFilename());
                file1.setDirectoryId(directoryId == null ? 2 : directoryId);
                file1.setFileSize(file.getSize() + "B");
                file1.setTypeId(1);
                file1.setMd5(md5Hex);
                int insert = fileService.insertSelective(file1);
                return insert > 0 ? AjaxResult.success(file1) : AjaxResult.fail("上传失败");
            } else {
                return AjaxResult.fail("文件已经存在");
            }

        }
        // 上传的目录就是 根目录 + 用户名 + 目录名
        return AjaxResult.fail("请选择文件后进行上传");
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response, Integer id) throws IOException {
        com.kfm.entity.File file = fileService.selectByPrimaryKey(id);
        if (file != null) {
            // 根目录 + / + 用户名 + / + 目录名 + / + 文件名
            String path = FileConfig.getLocalPath() + File.separator + file.getUser().getUsername() + File.separator
                    + file.getDirectory().getDirectoryName() + File.separator + file.getFileName();
            System.out.println(path);
            File file1 = new File(path);
            InputStream in = new FileInputStream(file1);
            // 设置响应头，以附件形式下载 文件下载
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            // 设置文件下载的名称
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8));
            in.transferTo(response.getOutputStream());
            in.close();
        }
    }

    @GetMapping("/readFile")
    public AjaxResult readFile(Integer id) throws IOException {
        com.kfm.entity.File file = fileService.selectByPrimaryKey(id);
        if (file != null) {
            String path = FileConfig.getLocalPath() + File.separator + file.getUser().getUsername() + File.separator
                    + file.getDirectory().getDirectoryName() + File.separator + file.getFileName();
            File f = new File(path);
            InputStream in = new FileInputStream(f);
            byte[] bytes = in.readAllBytes();
            if (bytes == null) {
                return AjaxResult.fail();
            }
            return AjaxResult.success(new String(bytes));
        }
        return AjaxResult.fail("文件不存在");
    }

}
